use crate::state::{Action, Comment, Event, State};
use chrono::NaiveDate;
use yew::prelude::*;
use yew_store::StoreLink;

pub struct Model {
    store: StoreLink<State, Action>,
    link: ComponentLink<Self>,
}

#[derive(Properties)]
pub struct Props {
    #[props(required)]
    pub store: StoreLink<State, Action>,
}

pub enum Msg {
    StoreEvent(Event),
}

impl Component for Model {
    type Message = Msg;
    type Properties = Props;

    fn create(props: Self::Properties, mut link: ComponentLink<Self>) -> Self {
        let callback = link.send_back(|event| Msg::StoreEvent(event));
        Model {
            store: props.store.reform(Some(callback)),
            link,
        }
    }

    fn update(&mut self, msg: Self::Message) -> ShouldRender {
        match msg {
            Msg::StoreEvent(_) => (),
        }
        true
    }

    fn change(&mut self, props: Self::Properties) -> ShouldRender {
        let callback = self.link.send_back(|event| Msg::StoreEvent(event));
        self.store = props.store.reform(Some(callback));
        true
    }
}

impl Renderable<Model> for Model {
    fn view(&self) -> Html<Self> {
        let state = self.store.state();
        html! {
            <div>
                <header class="text-gray-800">{"日志动态"}</header>
                // {for state.comments.iter().rev().map(|(date, daliy_comments)| self.daliy_comment_view(date, daliy_comments))}
                <ul>
                    {for state.comments.iter().map(|comment| self.comment_view(comment)) }
                </ul>
            </div>
        }
    }
}

impl Model {
    fn daliy_comment_view(&self, date: &NaiveDate, comments: &Vec<Comment>) -> Html<Self> {
        html! {
            <ul>
                <li class="flex justify-start my-2"><span class="text-gray-400 text-xs">{date.format("%Y年%m月%d日").to_string()}</span></li>
                {for comments.iter().map(|comment| self.comment_view(comment))}
            </ul>
        }
    }

    fn comment_view(&self, comment: &Comment) -> Html<Self> {
        let cid = comment.id;
        let item_classes = self
            .store
            .state()
            .selected_task_id
            .filter(|&tid| tid == cid)
            .map(|_| "text-blue-600")
            .unwrap_or("");
        html! {
            <li class="flex flex-col border rounded bg-orange-100 border-orange-400 p-2 my-2">
                <p class="column">{comment.description.as_str()}</p>
                <div class="text-gray-400 text-xs self-end">{comment.created_at.to_string()}</div>
            </li>
        }
    }
}
